package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.PayPlanSheetUserDao;
import com.xbongbong.saas.domain.entity.PayPlanSheetUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PayPlanSheetUserModel;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/4/11 15:13
 * @since v1.0
 */
@Component
@Service("payPlanSheetUserModel")
public class PayPlanSheetUserModelImpl implements PayPlanSheetUserModel {
    @Resource
    private PayPlanSheetUserDao payPlanSheetUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private PayPlanSheetModel payPlanSheetModel;


    @Override
    public List<PayPlanSheetUserEntity> findEntitys(Map<String, Object> param) {
        return payPlanSheetUserDao.findEntitys(param);
    }

    @Override
    public Integer save(PayPlanSheetUserEntity PayPlanUserEntity) throws XbbException {
        return null;
    }

    @Override
    public PayPlanSheetUserEntity getByKey(Long key, String corpid) {
        return payPlanSheetUserDao.getByKey(key, corpid);
    }

    @Override
    public List<PayPlanSheetUserEntity> findAllEntitys(Map<String, Object> param) {
        return null;
    }

    @Override
    public void disbandedTeamByCustomerId(String corpid, List<Long> customerIdList) throws XbbException {

    }

    @Override
    public void delete(PayPlanSheetUserEntity payPlanSheetUserEntity) throws XbbException {
        payPlanSheetUserEntity.setDel(1);
        payPlanSheetUserEntity.setUpdateTime((long) DateUtil.getInt());
        payPlanSheetUserDao.update(payPlanSheetUserEntity);
        paasEsModel.update(payPlanSheetUserEntity,IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM,payPlanSheetUserEntity.getCorpid(),payPlanSheetUserEntity.getId(),payPlanSheetUserEntity.getDataId());
    }

    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return payPlanSheetUserDao.findBaseEntitys(map);
    }

    @Override
    public Integer deleteByPurchaseIdIn(List<Long> purchaseIdIn, String corpid) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("payPlanIdIn", purchaseIdIn);
        List<PayPlanSheetUserEntity> payPlanSheetUserEntities = findEntitys(map);
        payPlanSheetUserDao.deleteByDataIdIn(purchaseIdIn, corpid);
        for (PayPlanSheetUserEntity entity : payPlanSheetUserEntities) {
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM,entity.getDataId());
        }
        return null;
    }

    @Override
    public List<Long> getDataIdList(String corpid, Integer isMain, List<String> userId) {
        return null;
    }

    @Override
    public void insertBatch(List<PayPlanSheetUserEntity> payPlanSheetUserEntityList) throws XbbException {
        insertBatch(payPlanSheetUserEntityList, WriteRequest.RefreshPolicy.NONE);
    }

    @Override
    public void insertBatch(List<PayPlanSheetUserEntity> payPlanSheetUserEntityList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        payPlanSheetUserDao.insertBatch(payPlanSheetUserEntityList);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM, payPlanSheetUserEntityList);

        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.insertBatch(insertDTOList, refreshPolicy);
    }
    
    @Override
    public void insertBatch(List<PayPlanSheetUserEntity> payPlanSheetUserEntityList,boolean needThrow) throws XbbException {
        payPlanSheetUserDao.insertBatch(payPlanSheetUserEntityList);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM, payPlanSheetUserEntityList);

        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.insertBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE,needThrow);
    }
    
    @Override
    public void batchDelete(String corpid, List<PayPlanSheetUserEntity> removeList,boolean needThrow) throws XbbException {
        List<Long> removeIdList = new ArrayList<>();
        removeList.forEach(entity -> removeIdList.add(entity.getId()));
        payPlanSheetUserDao.batchDeleteById(corpid, removeIdList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PayPlanSheetUserEntity entity : removeList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM.getType());
            Map<String,Object> sourceMap = new HashMap<>();
            sourceMap.put(StringConstant.DEL,DelEnum.DELETE.getDel());
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList,WriteRequest.RefreshPolicy.NONE,needThrow);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del,boolean needThrow) throws XbbException {
        batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, del, needThrow, WriteRequest.RefreshPolicy.NONE);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        payPlanSheetUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }

    @Override
    public Integer insert(PayPlanSheetUserEntity entity) throws XbbException {
        return null;
    }

    @Override
    public Integer update(PayPlanSheetUserEntity entity) throws XbbException {
        return null;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return payPlanSheetUserDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    /**
     * 更新协同人可编辑权限
     *
     * @param payPlanSheetUserEntity
     */
    @Override
    public void updateEditFormPer(PayPlanSheetUserEntity payPlanSheetUserEntity) throws XbbException {
        updateFormTeam(payPlanSheetUserEntity);
    }

    /**
     * 编辑标签
     *
     * @param payPlanSheetUserEntity
     * @throws XbbException
     */
    @Override
    public void editLabel(PayPlanSheetUserEntity payPlanSheetUserEntity) throws XbbException {
        updateFormTeam(payPlanSheetUserEntity);
    }

    private void updateFormTeam(PayPlanSheetUserEntity payPlanSheetUserEntity) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        payPlanSheetUserEntity.setUpdateTime(updateTime);
        payPlanSheetUserDao.update(payPlanSheetUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = payPlanSheetUserEntity.getCorpid();
        insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM.getType() + "_" + corpid + "_" + payPlanSheetUserEntity.getId());
        insertDTO.setParent(corpid + "_" + payPlanSheetUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM);
        paasEsModel.update(insertDTO);
    }

    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param idIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, idIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        payPlanSheetUserDao.batchUpdateCoAndPerByUserIdIn(corpid, idIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }

    @Override
    public List<PayPlanSheetUserEntity> getPaySheetUserIdList(String corpid, Long paySheetId, Integer isMain) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put("dataId", paySheetId);
        param.put("isMain", isMain);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        return findEntitys(param);
    }

    /**
     * 更新付款单团队删除标识
     *
     * @param corpid
     * @param payPlanSheetUserEntities
     * @param del
     * @throws XbbException
     */
    @Override
    public void deleteBatchUser(String corpid, List<PayPlanSheetUserEntity> payPlanSheetUserEntities, Integer del) throws XbbException {
        if (CollectionsUtil.isEmpty(payPlanSheetUserEntities)) {
            return;
        }
        List<Long> idList = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.DEL, del);
        for (PayPlanSheetUserEntity entity : payPlanSheetUserEntities){
            idList.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_TEAM.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
        }
        payPlanSheetUserDao.deleteBatchByIdList(idList, corpid, del);
        paasEsModel.updateBatch(insertDTOList);
    }

}
